//
//  SOSContactDetailViewController.m
//  leo
//
//  Created by YU-LIN LIU on 12/30/15.
//  Copyright © 2015 mdx. All rights reserved.
//

#import "SOSContactDetailViewController.h"

#import "SyncManager.h"
#import "DataManager.h"
#import "LeoMsg.h"
#import "AppDelegate.h"


@interface SOSContactDetailViewController ()

@property (nonatomic,retain) SyncManager *syncManager;
@property (nonatomic,retain) DataManager *dataManager;

@end

@implementation SOSContactDetailViewController

@synthesize nameLabel;
@synthesize headImage;
@synthesize phoneLabel;
@synthesize manager;
@synthesize contact;
@synthesize deleteButton;

-(void)dealloc
{
    manager=NULL;
    contact=NULL;
    self.syncManager=NULL;
    self.dataManager=NULL;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.title=@"紧急联系人";
    //self.navigationItem.rightBarButtonItem=self.navRightButton;
    [self initDataProxy];
    [self initData];
    
    [deleteButton addTarget:self action:@selector(deleteContact) forControlEvents:UIControlEventTouchUpInside];
    

    // Do any additional setup after loading the view from its nib.
}
-(void)initDataFromManager
{
    
    User *user=[User sharedSingleton];
    if(user!=NULL&&[user.uid isEqualToString:manager.user_id])
    {
        deleteButton.hidden=YES;
    }

    phoneLabel.text=manager.phone;
    nameLabel.text=manager.nickName;
    

    
    NSRange range;
    NSString *photoNameString;
    range = [manager.pic_url rangeOfString:@"/headimg/"];
    if (range.location != NSNotFound) {
        NSLog(@"found at location = %d, length = %d",range.location,range.length);
        photoNameString=[manager.pic_url substringFromIndex:range.location];
        NSLog(@"%@",photoNameString);
        
    }else{
        NSLog(@"Not Found");
    }
    
    
    if(manager.pic_url!=NULL&&![manager.pic_url isEqualToString:@"(null)"]&&![manager.pic_url isEqualToString:@""])
    {
        NSString *headUrl=[NSString stringWithFormat:@"%@%@",[Tooler getDocumentDirectory],photoNameString];
        headImage.image=[UIImage imageWithContentsOfFile:headUrl];
    }
    else
    {
        headImage.image = [UIImage imageNamed:@"avater_brother"];
    }
    
    
    
}

-(void)initData
{
    if (manager!=nil)
    {
        [self initDataFromManager];
        return;
    }
    
    phoneLabel.text=contact.phoneNum;
    nameLabel.text=contact.contactname;
    
    NSURL *url = [NSURL URLWithString:(contact.photo_url)];
    NSData *avatarImageData = [NSData dataWithContentsOfURL:url];
    
    NSRange range;
    NSString *photoNameString;
    range = [contact.photo_url rangeOfString:@"/headimg/"];
    if (range.location != NSNotFound) {
        NSLog(@"found at location = %d, length = %d",range.location,range.length);
        photoNameString=[contact.photo_url substringFromIndex:range.location];
        NSLog(@"%@",photoNameString);
        
    }else{
        NSLog(@"Not Found");
    }
    
    
    if(contact.photo_url!=NULL&&![contact.photo_url isEqualToString:@"(null)"]&&![contact.photo_url isEqualToString:@""])
    {
        NSString *headUrl=[NSString stringWithFormat:@"%@%@",[Tooler getDocumentDirectory],photoNameString];
        headImage.image=[UIImage imageWithContentsOfFile:headUrl];
    }
    else
    {
        headImage.image = [UIImage imageNamed:@"avater_brother"];
    }

}
-(void)initDataProxy{
    self.syncManager=[[SyncManager alloc] init];
    self.dataManager=[[DataManager alloc] init];
}


-(void)viewWillAppear:(BOOL)animated
{
    //头像切圆代码
    self.headImage.layer.cornerRadius = 120 / 2;
    self.headImage.clipsToBounds = YES;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)deleteManager{
    
    if (manager.type==1){
        [LeoMsg showMsg:@"主管理员必须为紧急联系人!"];
        return;
    }
    else{
        User *user=[User sharedSingleton];
        NSString *userId=user.uid;
        Watch *watch=[self.dataManager getActiveWatch:userId];
        NSString *watchId=watch.deviceUid;
        
        Manager *manager1=[self.dataManager getManager:manager.manager_id];
        //NSLog(@"第%d次%@",i,[dic valueForKey:@"contact_id"]);
        //manager1.type=0; // 上传服务器时，1是紧急联系人  4是普通联系人?
        //NSLog(@"第%d次%@",i,contact1.contactname);
        manager1.isSos=0;
        [self.syncManager updateViceAdminInfo:watchId viceAdmin:manager1 completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
            if(result==SUCESS)
            {
                [self.navigationController popViewControllerAnimated:YES];
            }
            else {
                [Tooler showHttpMsg:result description:description msg:@"删除紧急联系人失败"];
            }

            
        }];
        
        
        
//        [self.syncManager setWatchContact:manager1 completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
//            if(result==SUCESS)
//            {
//                [self.navigationController popViewControllerAnimated:YES];
//            }
//            else if (result==false){
//                if(description!=NULL)
//                    [LeoMsg showMsg:description];
//                else
//                    [LeoMsg showMsg:@"删除紧急联系人失败"];
//            }
//        }];

        
    }
}
- (void)deleteContact{
    
    if (manager!=nil)
    {
        [self deleteManager];
        //[LeoMsg showMsg:@"主管理员必须为紧急联系人!"];
        return;
    }
    
    NSLog(@"%@",contact.contact_id);
    NSLog(@"%@",contact.contactname);
    
    Contact *contact1=[self.dataManager getContact:contact.contact_id];
    //NSLog(@"第%d次%@",i,[dic valueForKey:@"contact_id"]);
    contact1.type=4; // 上传服务器时，1是紧急联系人  4是普通联系人?
    //NSLog(@"第%d次%@",i,contact1.contactname);

    [self.syncManager setWatchContact:contact1 completion:^(SyncResult result, NSDictionary *retValue, NSString *description) {
        if(result==SUCESS)
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
        else {
            [Tooler showHttpMsg:result description:description msg:@"删除紧急联系人失败"];
        }
    }];
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
